package com.streamhub.client;

import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.formatters.BarFormat;
import com.google.gwt.visualization.client.formatters.ColorFormat;
import com.google.gwt.visualization.client.formatters.NumberFormat;
import com.google.gwt.visualization.client.visualizations.Table;
import com.google.gwt.visualization.client.visualizations.Table.Options;
import com.google.gwt.visualization.client.visualizations.Table.Options.Policy;

public class Stock implements StreamHubGWTUpdateListener {
	private final String symbol;
	private final String company;
	private final double initialPrice;
	private int dataTableRow;
	private DataTable dataTable;
	private Table dataTableWrapper;

	public Stock(String symbol) {
		this.symbol = symbol;
		this.company = "-";
		this.initialPrice = 0.0;
	}
	
	public void onUpdate(String topic, JSONObject update) {
		if (symbol.equals(topic)) {
			String lastPrice = ((JSONString)update.get("LastPrice")).stringValue();
			String companyName = ((JSONString)update.get("Company")).stringValue();
			String percentChange = ((JSONString)update.get("PercentChange")).stringValue();
			String change = ((JSONString)update.get("Change")).stringValue();
			Double changeDouble = Double.valueOf(change);
			
			dataTable.setValue(dataTableRow, 1, companyName);
			dataTable.setValue(dataTableRow, 2, Double.valueOf(lastPrice));
			dataTable.setValue(dataTableRow, 3, changeDouble);
			dataTable.setValue(dataTableRow, 4, Double.valueOf(percentChange.replace("%", "")));
			
			formatData();
			reDrawTable();
		}
	}
	
	public void addToDataTable(DataTable dataTable, Table dataTableWrapper) {
		this.dataTable = dataTable;
		this.dataTableWrapper = dataTableWrapper;
		dataTable.addRow();
		dataTableRow = dataTable.getNumberOfRows() - 1;
		dataTable.setValue(dataTableRow, 0, symbol);
		dataTable.setValue(dataTableRow, 1, company);
		dataTable.setValue(dataTableRow, 2, initialPrice);
		dataTable.setValue(dataTableRow, 3, 0.04);
		dataTable.setValue(dataTableRow, 4, 23.3);
	}
	
	private void formatData() {
		NumberFormat numberFormat = NumberFormat.create(NumberFormat.Options.create());
		numberFormat.format(dataTable, 3);
		ColorFormat colorFormat = ColorFormat.create();
		colorFormat.addRange(-999999.0, -0.00001, "red", null);
		colorFormat.addRange(0.0, 999999.0, "green", null);
		colorFormat.format(dataTable, 3);
		colorFormat.format(dataTable, 4);
		BarFormat barFormat = BarFormat.create(BarFormat.Options.create());
		barFormat.format(dataTable, 4);
	}

	private void reDrawTable() {
		Options options = Options.create();
		options.setSort(Policy.DISABLE);
		options.setOption("allowHtml", true);
		dataTableWrapper.draw(dataTable, options);
	}
}
